package com.hengfoxwolf.ffmpegdemo
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.View
import com.hengfoxwolf.ffmpegdemo.base.BaseActivity
import com.hengfoxwolf.ffmpegdemo.databinding.ActivityAudioPlayBinding
import com.hengfoxwolf.ffmpegdemo.util.AudioSLPlayer
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class AudioPlayActivity :
    BaseActivity<ActivityAudioPlayBinding>(ActivityAudioPlayBinding::inflate),View.OnClickListener,AudioSLPlayer.AudioSLPlayerCallback {

    private lateinit var slPlayer: AudioSLPlayer

    private lateinit var mediaPath: String

    private var firstPlay = true
    private var playPause = true

    override fun init(savedInstanceState: Bundle?) {

        slPlayer = AudioSLPlayer()
        slPlayer.init()
        slPlayer.setAudioSLPlayerCallback(this)
        mediaPath = Environment.getExternalStorageDirectory().path + "/define/mua1.mp3"

        mBinding.btnPlayPause.setOnClickListener(this)
    }

    override fun onStop() {
        super.onStop()
        launch(Dispatchers.IO) {
            slPlayer.stop()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        launch(Dispatchers.IO) {
            slPlayer.destroy()
        }
    }

    override fun onClick(view: View?) {
        when (view?.id) {
            R.id.btn_play_pause -> {
                if (firstPlay) {
                    slPlayer.stop()
                    slPlayer.play(mediaPath)
                    firstPlay = false
                    mBinding.btnPlayPause.text = resources.getString(R.string.txt_pause)
                } else {
                    mBinding.btnPlayPause.text = resources.getString(if (playPause) R.string.txt_play else R.string.txt_pause)
                    slPlayer.playPause(playPause)
                    playPause = !playPause
                }
            }
        }
    }

    override fun onAudioSLPlayerCallback() {
        Log.d(TAG, "--onAudioSLPlayerCallback--")
    }

    companion object {
        const val TAG = "AudioPlayActivity"
    }

}